'''
Created on 09/03/2011

@author: andrew
'''
from MusicFile import MusicFile
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3
import mutagen.id3

class MP3file(MusicFile):
    '''
    Extract MP3 informations.
    Install dependencies:
        yum install python-mutagen
    '''
    def __init__(self,path):
        '''
        Constructor
        '''
        MusicFile.__init__(self,path)
        try:
            mutagen.id3.ID3(self.path)
        except:
            raise ValueError('Invalid MP3 file: '+self.path)
        else:
            self.mp3 = MP3(self.path, ID3=EasyID3)
            #Adicionando estrutura das tags caso nao exista
            try:
                if self.writable: self.mp3.add_tags(ID3=EasyID3)
            except mutagen.id3.error:
                #Erro quando ja existe tags ID3
                pass

    @property
    def album(self):
        return self.mp3['album'][0] if self.mp3.has_key('album') else ""

    @album.setter
    def album(self,album):
        if not(self.writable): raise IOError("Permission denied") 
        self.mp3["album"] = album
        self.mp3.save()

    @property
    def artist(self):
        return self.mp3['artist'][0] if self.mp3.has_key('artist') else ""

    @artist.setter
    def artist(self,artist):
        if not(self.writable): raise IOError("Permission denied") 
        self.mp3["artist"] = artist
        self.mp3.save()

    @property
    def title(self):
        return self.mp3['title'][0] if self.mp3.has_key('title') else ""

    @title.setter
    def title(self,title):
        if not(self.writable): raise IOError("Permission denied") 
        self.mp3["title"] = title
        self.mp3.save()

    @property
    def sampleRate(self):
        return self.mp3.info.sample_rate

    @property
    def bitRate(self):
        return self.mp3.info.bitrate / 1000

    @property
    def length(self):
        secs = int(self.mp3.info.length)
        mins = secs / 60
        secs = secs - mins * 60
        return "%d:%02d" % (mins, secs)

    def __repr__(self):
        for k, v in self.mp3.items():
            print k, ":", v
        return ""
